<template>
  <div :class="['wrap', pageTitle === '音频' ? 'bgWhite': '' ]">
    <div v-if="pageTitle === '海报' || pageTitle === '图片'">
      <div :style="{background: `url(${shareData.content})`,width: '750rpx', height: `${shareData.imgHeight}rpx`, backgroundSize:'contain'}" />
    </div>
    <div v-if="pageTitle === '文档'">
      <div class="doc_img">
        <Icon :name="iconName" height="280" width="224" />
      </div>
      <div class="doc_text">{{ materialDetails.abstract }}</div>
      <div class="doc_btn flex_cen_cen" @tap="downloadArticle(materialDetails)">
        <Icon name="icon-xiazaidaoru" size="36" />
        <span>下载</span>
      </div>
    </div>
    <div v-if="pageTitle === '视频'">
      <video
        :src="`${baseUrl}/${materialDetails.content}`"
        :style="{width: '100vw', height: `calc(100vh - 120rpx)`}"
        play-btn-position="center"
      />
    </div>
    <div v-if="pageTitle === '音频' && materialDetails.content">
      <Paudio
        :audio-id="`audio${materialDetails.materialId}`"
        :title="materialDetails.title"
        :url="`${baseUrl}/${materialDetails.content}`"
      />
    </div>
    <div class="foot">
      <div class="foot-btn">
        <Icon name="icon-reading" size="50" style="margin-right: 20rpx;" />
        <div>阅读</div>
        <div>{{ materialDetails.totalReadingCount }}</div>
      </div>
      <div :class="{ 'foot-btn-act': isLike }" class="foot-btn" @tap.stop="likeFn">
        <Icon v-if="isLike" name="icon-like-act" size="40" style="margin-right: 20rpx;" />
        <Icon v-else name="icon-like" size="40" style="margin-right: 20rpx;" />
        <div>赞</div>
        <div>{{ materialDetails.totalLikingCount }}</div>
      </div>
    </div>
    <div v-if="pageTitle === '视频' || pageTitle === '音频'" :style="{paddingBottom: `${storeState.bottomSafeDis}rpx`}" class="video_audio flex_cen_cen">
      <template v-if="!isShareEnter">
        <button class="video_audio_btn" open-type="share" style="margin-right: 254rpx;" @tap="shareFn">
          <div class="flex_sb_cen">
            <Icon name="icon-fenxiang1" size="30" />
            <span style="margin-left: 8rpx">分享</span>
          </div>
        </button>
        <button class="video_audio_btn" @tap="downloadFn">
          <div class="flex_sb_cen">
            <Icon name="icon-xiazaidaoru" size="36" />
            <span style="margin-left: 8rpx">下载</span>
          </div>
        </button>
      </template>
      <template v-else>
        <button class="btn_solid" style="margin-right: 38rpx" @tap="showConsult = true">问题咨询</button>
        <button class="btn_primary" @tap="goTel(consultFormData.transferMobile)">拨打电话</button>
      </template>
    </div>
    <div v-else :style="{paddingBottom: `${storeState.bottomSafeDis}rpx`}" class="suction_bottom_btn">
      <template v-if="!isShareEnter">
        <button class="btn_solid" style="margin-right: 38rpx" @tap="showData = true">查看数据</button>
        <button class="btn_primary" open-type="share" @tap="shareFn">分享</button>
      </template>
      <template v-else>
        <button class="btn_solid" style="margin-right: 38rpx" @tap="showConsult = true">问题咨询</button>
        <button class="btn_primary" @tap="goTel(consultFormData.transferMobile)">拨打电话</button>
      </template>
    </div>
    <!--  数据汇总  -->
    <u-popup :show="showData" closeable overlay-opacity="0.45" round="12" safe-area-inset-bottom @close="showData = false">
      <div class="popup_box">
        <div class="popup_title">数据汇总</div>
        <div class="popup_body">
          <div class="data flex_sb_cen">
            <div v-for="(item, index) in dataConfig" :key="index" class="data_item" @tap="jumpToPageFn(item)">
              <div :style="{color: item.title === '表单' ? '#1890FF' : '' }" class="data_num">{{ item.num }}</div>
              <div class="data_name">{{ item.title }}</div>
            </div>
          </div>
          <div class="btn_solid" style="width: 100%;" @tap="showData = false">关闭</div>
        </div>
      </div>
    </u-popup>
    <!--  问题咨询  -->
    <u-popup :show="showConsult" closeable overlay-opacity="0.45" round="12" safe-area-inset-bottom @close="showConsult = false">
      <div class="popup_box">
        <div class="popup_title">问题咨询</div>
        <div class="popup_body">
          <div class="popup_name">姓名</div>
          <up-input
            v-model="consultFormData.name"
            :custom-style="{background: '#F5F6F7'}"
            border="surround"
            placeholder="信息已加密，请放心填写"
          />
          <div class="popup_name">电话号码</div>
          <up-input
            v-model="consultFormData.mobile"
            :custom-style="{background: '#F5F6F7'}"
            border="surround"
            maxlength="11"
            placeholder="信息已加密，请放心填写"
            type="number"
          />
          <div class="popup_name">想要咨询的问题</div>
          <u--textarea
            v-model="consultFormData.question"
            :custom-style="{background: '#F5F6F7'}"
            height="314rpx"
            placeholder="信息已加密，请放心填写"
          />
          <button :disabled="!isDisabled" class="btn_primary" style="width: 100%;margin-top: 60rpx;" @tap="commitFn">提交</button>
        </div>
      </div>
    </u-popup>
  </div>
</template>
<script lang="ts" setup>
import {
  storeState,
  onLoad,
  onShareAppMessage,
  Router,
  obj_oto_query,
  downloadVideo,
  copyToClipboard,
  checkPhoneFn,
} from '@U/common'
import { ref, reactive, computed } from 'vue'
import goTel from '@U/goTel'
import Paudio from '@C/Paudio.vue'
import { getMaterialDetails, addDownloadingCount } from '@P_GL/ZhiKe/margetCenter/request'
import { Msg, MsgLoading, PMsgLoadingClean } from '@C/Msg'
import download from '@U/download'
import {
  addLikingCount,
  addReadingCount,
  addShareCount,
  commitMaterialForm,
  decreaseLikingCount,
} from '@P/Article/request'
import Icon from '@C/Icon.vue'

const isDisabled = computed(() => consultFormData.name && consultFormData.mobile && consultFormData.question)
const iconName = computed(() => {
      let temp = ''
      switch (materialDetails.value.content?.split('.')[1]) {
        case 'pdf': temp = 'icon-pdf-2'; break
        case 'doc':
        case 'docx': temp = 'icon-word-2'; break
        case 'xls':
        case 'xlsx': temp = 'icon-excel-2'; break
        case 'ppt':
        case 'pptx': temp = 'icon-ppt-2'; break
      }
      return temp
})
const baseUrl = import.meta.env.VITE_SHOUDAO_IMG_URL
const showData = ref(false)
const dataConfig = [
  {
    title: '浏览量',
    key: 'totalReadingCount',
    num: 0,
  },
  {
    title: '分享数量',
    key: 'totalTransferringCount',
    num: 0,
  },
  {
    title: '点赞数',
    key: 'totalLikingCount',
    num: 0,
  },
  {
    title: '表单',
    key: 'formCount',
    num: 0,
  },
]
const showConsult = ref(false)
const materialDetails = ref({})
// 获取素材详情
const getMaterialDetailsFn = async () => {
  await MsgLoading()
  const res = await getMaterialDetails({ materialId: materialId.value }).finally(() => {})
  if (res?.code === 200) {
    PMsgLoadingClean()
    materialDetails.value = res.data
    // 给数据汇总弹框赋值
    dataConfig.forEach(item => {
      const findItem = Object.keys(res.data).find(item1 => item1 === item.key)
      item.num = res.data[findItem]
    })
    materialDetails.value.pageTitle = pageTitle.value
  }
}
const isShareEnter = ref(false)
const pageTitle = ref('')
const materialId = ref('')
const consultFormData = reactive({
  name: '',
  mobile: '',
  question: '',
  materialId: '',
  transferIsChannelAgent: true,
  transferAccountId: '',
  transferMobile: '',
})
const shareData = ref({})
onLoad((options: any) => {
  pageTitle.value = options.pageTitle
  materialId.value = options.materialId
  uni.setNavigationBarTitle({
    title: `${options.pageTitle }详情`,
  })
  // 判断是否通过分享链接进入该页面
  if (uni.getLaunchOptionsSync().scene === 1007) {
    uni.getImageInfo({
      src: `${import.meta.env.VITE_SHOUDAO_IMG_URL}/${options.content}`,
      success: (image) => {
        options.imgHeight = image.height / (image.width / 750)
        options.content = `${import.meta.env.VITE_SHOUDAO_IMG_URL}/${options.content}`
        shareData.value = options
      },
    })
    isShareEnter.value = true
    consultFormData.materialId = options.materialId
    consultFormData.transferIsChannelAgent = options.transferIsChannelAgent
    consultFormData.transferAccountId = options.transferAccountId
    consultFormData.transferMobile = options.transferMobile
  }
  let ossName = ''
  switch (options.content?.split('.')[1]) {
    case 'pdf': ossName = 'share_pdf'; break
    case 'doc':
    case 'docx': ossName = 'share_word'; break
    case 'xls':
    case 'xlsx': ossName = 'share_excel'; break
    case 'ppt':
    case 'pptx': ossName = 'share_pdf'; break
    default: ossName = 'share_audio'
  }
  // 分享给朋友
  onShareAppMessage(() => {
    const articleDetailNew = JSON.parse(JSON.stringify(materialDetails.value))
    articleDetailNew.content = ''
    return ({
      path: `/page_gl/ZhiKe/margetCenterDetails?${obj_oto_query(articleDetailNew)}`,
      title: materialDetails.value.title,
      imageUrl: options.cover ? `${baseUrl}/${options.cover}` : `${import.meta.env.VITE_SHOUDAO_OSS_URL}/${ossName}.png`,
    })
  })
  // 增加阅读数
  addReadingCount({ materialId: options.materialId })
  getMaterialDetailsFn()
})
const jumpToPageFn = (item: object) => {
  if (item.title !== '表单') return
  if (item.num === 0) return
  Router.push('gl_market_form', { materialId: materialId.value })
}
// 点赞
const isLike = ref(false)
const likeFn = async () => {
  isLike.value = !isLike.value
  if (isLike.value) {
    await addLikingCount({ materialId: materialId.value }).finally(() => {})
    materialDetails.value.totalLikingCount += 1
  } else {
    await decreaseLikingCount({ materialId: materialId.value }).finally(() => {})
    materialDetails.value.totalLikingCount -= 1
  }
  // 更新数据汇总中的点赞数
  await getMaterialDetailsFn()
}
const downloadFn = async () => {
  if (pageTitle.value === '视频') return downloadVideo(materialDetails.value.content)
  if (pageTitle.value === '音频') {
    copyToClipboard({
      content: `${baseUrl}/${materialDetails.value.content}`,
      successTip: '链接复制成功,请前往浏览器下载',
      failTip: '链接复制失败',
    })
  }
}
const downloadArticle = async (info: any) => {
  await addDownloadingCount({ materialId: info.id })
  download(info.content, true, false, true)
}
const shareFn = () => {
  addShareCount({ materialId: materialId.value })
}
// 提交素材报表
const commitFn = async () => {
  if (!checkPhoneFn(consultFormData.mobile)) return Msg({ msg: '手机号格式不正确' })
  await MsgLoading()
  const res = await commitMaterialForm(consultFormData).finally(() => {})
  if (res?.code === 200) {
    PMsgLoadingClean()
    Msg({ msg: '提交成功' })
    showConsult.value = false
  }
}
</script>
<style lang="less">
page {
  background-color: #f2f2f7;
  padding-top: 2rpx;
  box-sizing: border-box;
}
</style>
<style lang="less" scoped>
.bgWhite {
  background-color: #fff;
}
.doc_img {
  width: 224rpx;
  height: 280rpx;
  margin: 140rpx auto 54rpx;
}
.doc_text {
  width: 644rpx;
  font-size: 32rpx;
  font-weight: 400;
  color: rgba(0,0,0,0.85);
  line-height: 48rpx;
  margin: 0 auto 76rpx;
}
.doc_btn {
  width: 390rpx;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  font-size: 36rpx;
  color: #1890ff;
  background: #FFFFFF;
  border-radius: 40rpx;
  border: 2rpx solid #1890FF;
  margin: 0 auto;
}
.popup_box {
  .data {
    margin: 60rpx 0;
    .data_item {
      width: 150rpx;
      text-align: center;
      .data_num {
        font-size: 48rpx;
        font-weight: 500;
        color: rgba(0,0,0,0.65);
        line-height: 66rpx;
      }
      .data_name {
        font-size: 28rpx;
        font-weight: 400;
        color: rgba(0,0,0,0.45);
        line-height: 40rpx;
      }
    }
  }
}
.video_audio {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100vw;
  padding-top: 28rpx;
  background-color: #fff;
  box-shadow: 4rpx -4rpx 12rpx 0rpx rgba(0,0,0,0.05);
  .video_audio_btn {
    font-size: 36rpx;
    font-weight: 400;
    color: rgba(0,0,0,0.65);
    line-height: 52rpx;
  }
}
.foot{
  height: 140rpx;
  display: flex;
  align-items: center;
  margin-bottom: 120rpx;
  .foot-btn{
    height: 140rpx;
    color: #bfbfbf;
    display: flex;
    align-items: center;
    font-size: 30rpx;
    margin:0 30rpx;
  }
  .foot-btn-act {
    color: #1890FF;
  }
}
</style>
